#!/bin/sh

TESTS="$@"

DIR=`dirname $0`
[ x$DIR = x ] && DIR="."

if [ x$TERM = xlinux ] || [ x$TERM = xxterm ]; then
    GREEN="\033[1;32m"
    RED="\033[1;31m"
    HIGH="\033[1m"
    CLEAR="\033[0m"
else
    GREEN=""
    RED=""
    HIGH=""
    CLEAR=""
fi

function usage ()
{
    echo -e "Usage:\n\t$0 [test1 ... testN]\n\n"
}


function showtestinfo ()
{
    SOURCE=$1
    DESC=$(grep -e "^ [*] DESC: " $SOURCE | sed 's/^ [*] DESC:[ \t]*\(.*\)[ \t]*$/\1/' )
    IMP=$(grep -e "^ [*] IMP: " $SOURCE | sed 's/^ [*] IMP:[ \t]*\(.*\)[ \t]*$/\1/' )
    echo -e "${HIGH}Description:${CLEAR} $DESC"
    echo -e "${HIGH}Impact.....:${CLEAR} $IMP"
}


function success ()
{
    SOURCE=$1
    LOG=$2
    echo -e "${GREEN}OK${CLEAR}"
}

function failed ()
{
    SOURCE=$1
    LOG=$2
    echo -e "${RED}FAILED${CLEAR}"
    showtestinfo $1
    echo
    echo -e "${HIGH}---=[ BEGIN: LOG ($LOG) ]=------------ --- -- -${CLEAR}"
    cat $LOG
    echo -e "${HIGH}---=[ END: LOG ]=------------ --- -- -${CLEAR}"
    echo

}


function runtest ()
{
    SOURCE=$1
    BIN=${SOURCE/%.c/}
    LOG="/tmp/$(basename $BIN).log"
    echo -e "Testing: $BIN"
    sh -c $BIN 2>$LOG && success $SOURCE $LOG || failed $SOURCE $LOG
    echo
}




if [ x$TESTS = x ]; then
    TESTS=`ls -1 $DIR/[0-9]*-*.c`
fi

for t in $TESTS; do
    case $t in
	(-h|--help)
	usage
	;;
	(*)
	runtest $t
	;;
    esac
done
